package net.akkz.dbFactory.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.akkz.dbFactory.DbManage;
import net.akkz.dbFactory.Session;
import net.akkz.dbFactory.SessionProxy;
import net.akkz.exception.SQLExcuteException;

public class SessionProxyImpl implements SessionProxy
{
	private Object target;
	private DbManage dbManage;

	public void setDbManage(DbManage dbManage)
	{
		this.dbManage = dbManage;
	}
	
	public void setTarget(Object o)
	{
		this.target = o;
	}
	
	public <T> T excute(String method, Object[] values) throws SQLExcuteException
	{
		Session session = dbManage.createSession();
		
		try
		{
			@SuppressWarnings("unchecked")
			T t = (T) target.getClass().getMethod(method, session.getClass(), Object[].class).invoke(target, session, values);
			
			session.commit();
			
			return t;
		}
		catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e)
		{
			session.rollback();
			Logger.getLogger(target.getClass().getName()).log(Level.SEVERE, null, e);
			
			throw new SQLExcuteException(e);
		}
	}
	
	public <T> T excute(String method) throws SQLExcuteException
	{
		Session session = dbManage.createSession();
		
		try
		{
			@SuppressWarnings("unchecked")
			T t = (T) target.getClass().getMethod(method, session.getClass()).invoke(target, session);
			
			session.commit();
			
			return t;
		}
		catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e)
		{
			session.rollback();
			Logger.getLogger(target.getClass().getName()).log(Level.SEVERE, null, e);
			
			throw new SQLExcuteException(e);
		}
	}
}
